import axios, { AxiosInstance, AxiosError, AxiosRequestConfig, InternalAxiosRequestConfig, AxiosResponse } from "axios";
import { showFullScreenLoading, tryHideFullScreenLoading } from "@/config/axiosLoading";
import { ElMessage } from "element-plus";
import { ResultData } from "@/api/interface";
import { ResultEnum } from "@/enums/index";
import { useUserStore } from "@/stores/modules/user";
import router from "@/routers";

export interface CustomAxiosRequestConfig extends InternalAxiosRequestConfig {
    noLoading?: boolean;
}


const config = {
    // 默认地址请求地址，可在 .env.** 文件中修改
    baseURL: import.meta.env.VITE_API_URL as string,
    // 设置超时时间
    timeout: 5000,
    // 跨域时候允许携带凭证
    withCredentials: true
};

class Request {
    service: AxiosInstance;
    public constructor(config: AxiosRequestConfig) {
        this.service = axios.create(config)

        this.service.interceptors.request.use(
            (config: any) => {
                const userStore = useUserStore();
                let user: any = localStorage?.getItem('user')
                let token = JSON.parse(user)?.token
                if (token === 'undefined') router.replace('/login');
                // 当前请求不需要显示 loading，在 api 服务中通过指定的第三个参数: { noLoading: true } 来控制
                config.noLoading || showFullScreenLoading();
                if (config.headers && typeof config.headers.set === "function") {
                    config.headers.set("Authorization", token);
                }
                return config;
            },
            (error: AxiosError) => {
                return Promise.reject(error);
            }
        );

        this.service.interceptors.response.use(
            (response: AxiosResponse) => {
                let { data } = response
                const userStore = useUserStore();
                tryHideFullScreenLoading();
                if (data.status == 203) {
                    userStore.setToken("");
                    router.replace('/login');
                    ElMessage.error(data.msg);
                    return Promise.reject(data);
                }
                /*  if (data.code && data.code !== ResultEnum.SUCCESS) {
                     ElMessage.error(data.msg);
                     return Promise.reject(data);
                 } */
                return data
            },
            async (error: AxiosError) => {
                const { response } = error;
                tryHideFullScreenLoading();
                // 请求超时 && 网络错误单独判断，没有 response
                if (error.message.indexOf("timeout") !== -1) ElMessage.error("请求超时！请您稍后重试");
                if (error.message.indexOf("Network Error") !== -1) ElMessage.error("网络错误！请您稍后重试");
                return Promise.reject(error);
            }
        );
    }

    /**
   * @description 常用请求方法封装
   */
    get<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
        return this.service.get(url, { params, ..._object });
    }
    post<T>(url: string, params?: object | string, _object = {}): Promise<ResultData<T>> {
        return this.service.post(url, params, _object);
    }
    put<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
        return this.service.put(url, params, _object);
    }
    delete<T>(url: string, params?: any, _object = {}): Promise<ResultData<T>> {
        return this.service.delete(url, { params, ..._object });
    }
    download(url: string, params?: object, _object = {}): Promise<BlobPart> {
        return this.service.post(url, params, { ..._object, responseType: "blob" });
    }
}


export default new Request(config);

